<?php
/**
 * CreateTime: 2024/1/15 17:27
 * User:LinQ
 */

namespace App\Http\Service\Wx;

use App\ApiCall\Wx\Applet\WxAppletExecute;
use App\Func\Company\CompanyFunc;
use App\Func\System\OperateLogFunc;
use App\Func\System\StrFunc;
use App\Models\Customers\CustomersModel;

class WxAppletService
{
    public function wxLogin($data){
        $res = (new WxAppletExecute())->jscode2session($data['js_code']);
        $fmtRes = json_decode($res);
        if(isset($fmtRes->errcode) && $fmtRes->errcode!=0){
            s_fail_return(null,$fmtRes->errmsg);
        }
        $customersModel = (new CustomersModel());
        $info = $customersModel->where('phone',$data['phone'])->where('status',1)->where('enable_status',1)->first();
        if(!$info){
            // 不存在则默认注册
            $puPvKey = rsa_pu_pv_key();
            $insertData = [
                'name' => (new StrFunc())->getRandomZhName(),
                'com_id' => (new CompanyFunc())->getCustomerComId(),
                'avatar_id' => -1,
                'union_id' => (\Symfony\Component\Uid\UuidV4::v6()->toRfc4122()),
                'enable_status' => 1,
                'phone' => $data['phone'],
                'wx_union_id' => $fmtRes->unionid,
                'wx_open_id' => $fmtRes->openid,
                'status' => 1,
                'pu_key' => $puPvKey['pu_key'],
                'pv_key' => $puPvKey['pv_key'],
            ];
            $customerId = $customersModel->insertGetId($insertData);
            // 添加操作记录
            OperateLogFunc::addCustomersOperate(
                'WxCustomersService',
                $customerId,
                'create',
                uid:$customerId);
            return $customerId;
        }
        // 存在查看是否绑定了账号
        if(!isset($info['wx_union_id'])&&!$info['wx_union_id']){
            $customersModel->where('customer_id',$info['customer_id'])->update([
                'phone' => $data['phone'],
                'wx_union_id' => $fmtRes->unionid,
                'wx_open_id' => $fmtRes->openid,
            ]);
            // 添加操作记录
            OperateLogFunc::addCustomersOperate(
                'WxCustomersService',
                $info['customer_id'],
                'bind',
                uid:$info['customer_id']);
        }
        return $info['customer_id'];
    }
}